package com.classnet.action.clazz;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.classnet.dao.ClazzDao;
import com.classnet.entity.ClazzEntity;
import com.classnet.entity.ClazzMenuEntity;
import com.classnet.util.page.WebUtil;

public class DownloadAction extends Action {

	private ClazzDao clazzDao;
	private String path;
	
	
	public void setPath(String path) {
		this.path = path;
	}


	public void setClazzDao(ClazzDao clazzDao) {
		this.clazzDao = clazzDao;
	}


	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		int id = WebUtil.getInteger(request, "id");
		ClazzEntity entity = clazzDao.selectById(ClazzEntity.class, id);
		if(entity!=null){
			File file = new File(path+"/files/"+entity.getFilename());
			if(!file.exists()){
				response.setCharacterEncoding("utf-8");
				response.getWriter().write("该文件不存在");
				return null;
			}
			response.reset();
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition","attachment;filename=" + new String(entity.getFilename().getBytes(),"ISO8859-1")); 
			OutputStream out = response.getOutputStream();
			FileInputStream in = new FileInputStream(file);
			byte[] b = new byte[1024];
			int i = 0;
			while((i=in.read(b))>0){
				out.write(b,0,i);
			}
			out.flush();
			in.close();
			out.close();
		}
		return null;
			
	}



	
}
